package com.moonspring.contronller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

import com.moonspring.dao.WebLogDao;
import com.moonspring.model.WebLogModel;


@WebListener
public class WebListenerContronller implements ServletContextListener,ServletRequestListener{

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
//		sce.get
		System.out.println("关闭服务");
	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("启动服务");
	}

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		System.out.println("request死亡");
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		long time = System.currentTimeMillis();
		String t = sdf.format(time);
		HttpServletRequest request = (HttpServletRequest) sre.getServletRequest();
		WebLogModel wlm = new WebLogModel();
		String type = request.getMethod();
		wlm.setType(type);
		wlm.setTime(t);
		String url = request.getRequestURL().toString();
		UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));   
		OperatingSystem os = userAgent.getOperatingSystem();  
		Browser browser = userAgent.getBrowser(); 
		String uri = request.getRequestURI();
		String fip = request.getRemoteAddr();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		String r = "err";
		if ("GET".equals(type)) {
			r = request.getQueryString();
			if(r!=null&&!r.isEmpty()){
				try {
					r = URLDecoder.decode(r,"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		} else {
			Map<String, String[]> re = request.getParameterMap();
			r = getParameterFormUrlEncoded(re).toString();
		}
		wlm.setIp(fip);
		wlm.setPattam(r);
		wlm.setRealIp(ip);
		wlm.setUrl(url);
		wlm.setUri(uri);
		wlm.setTime(t);
		wlm.setBrowser(browser.toString());
		wlm.setOs(os.toString());
		WebLogDao wld = new WebLogDao();
		wld.addWebLog(wlm);
	}
	private static Map<String, String> getParameterFormUrlEncoded(Map<String, String[]> properties){  
//      Map<?, ?> properties = request.getParameterMap();  
      Map<String, String> returnMap = new HashMap<String, String>();  
      Iterator<?> entries = properties.entrySet().iterator();  
      Entry<?, ?> entry;  
      String key = "";  
      String value = "";  
        
      while(entries.hasNext()){  
          entry = (Entry<?, ?>)entries.next();  
          key = (String)entry.getKey();  
          Object valueObj = entry.getValue();  
            
          if(null == valueObj){  
              value = "";  
          }else if(valueObj instanceof String[]){  
              String[] values = (String[])valueObj;  
              for(int i = 0;i < values.length;i++){  
                  value = values[i]+",";  
              }  
              value = value.substring(0, value.length()-1);   
          }else{  
              value = valueObj.toString();  
          }  
          returnMap.put(key, value);  
      }  
      return returnMap;  
 }  
}
